﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using RTW.Core.Helper;

namespace RTW.Core.Datas
{
    /// <summary>
    /// Dapper Helper
    /// create by ben.jiang 2017/5/21
    /// </summary>
    public partial class DapperHelperAsync
    {
        /// <summary>
        /// DB Connetction String
        /// </summary>
        static readonly string providers = AppSettingsManager.Get("DbContexts:DbType");
        private static readonly string connectionString = AppSettingsManager.Get($"DbContexts:{providers}:ConnectionString");
       
        public static IDbConnection Conn { get; set; }

        public DapperHelperAsync(IDbConnection connection)
        {
            Conn = connection;
        }

        public DapperHelperAsync()
        {
            switch (providers)
            {
                case "SqlClient":
                    // conn = new SqlConnection(connectionString);
                    break;
                case "SQLite":
                    Conn = new SQLiteConnection(connectionString);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(providers), providers, null);
            }
        }
        public void Dispose() => Conn.Dispose();

        /// <summary>
        /// Get Entity (int key)
        /// </summary> 
        public static async Task<T> GetAsync<T>(int id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
                

                    return await Conn.GetAsync<T>(id, transaction, commandTimeout);
 
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Get Entity (long key)
        /// </summary> 
        public static async Task<T> GetAsync<T>(long id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
               // using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.GetAsync<T>(id, transaction, commandTimeout);
                }
            }
            catch (Exception ex)
            {
               // SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Get Entity (guid key)
        /// </summary> 
        public static async Task<T> GetAsync<T>(System.Guid id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
                //using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.GetAsync<T>(id, transaction, commandTimeout);
                }
            }
            catch (Exception ex)
            {
               // SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Get Entity (string key)
        /// </summary> 
        public static async Task<T> GetAsync<T>(string id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
               // using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.GetAsync<T>(id, transaction, commandTimeout);
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Get All List
        /// </summary> 
        public static async Task<IEnumerable<T>> GetAllAsync<T>() where T : class, new()
        {
            try
            {
               // using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.GetAllAsync<T>();
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Get List With SQL
        /// </summary> 
        public static async Task<IEnumerable<T>> GetListAsync<T>(string sql) where T : class, new()
        {
            try
            {
               //using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.QueryAsync<T>(sql, commandType: CommandType.Text);
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Insert Entity
        /// </summary>
        public static async Task<int> InsertAsync<T>(T model, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
                //using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.InsertAsync<T>(model, transaction, commandTimeout);
                }
            }
            catch (Exception ex)
            {
               // SystemLog.WriteError(ex);
                return 0;
            }
        }
        /// <summary>
        /// Update Entity
        /// </summary>
        public static async Task<T> UpdateAsync<T>(T model, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
               // using (var conn = new SqlConnection(connectionString))
                {
                    bool b = await Conn.UpdateAsync<T>(model, transaction, commandTimeout);
                    if (b) { return model; }
                    else { return null; }
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        /// Delete Entity
        /// </summary>
        public static async Task<T> DeleteAsync<T>(T model, IDbTransaction transaction = null, int? commandTimeout = null) where T : class, new()
        {
            try
            {
                //using (var conn = new SqlConnection(connectionString))
                {
                    bool b = await Conn.DeleteAsync<T>(model, transaction, commandTimeout);
                    if (b) { return model; }
                    else { return null; }
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return null;
            }
        }
        /// <summary>
        ///Execute SQL Statement
        /// </summary> 
        public static async Task<int> ExecSqlAsync(string sql)
        {
            try
            {
                //using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.ExecuteAsync(sql);
                }
            }
            catch (Exception ex)
            {
                //SystemLog.WriteError(ex);
                return 0;
            }
        }

        #region For Project
        /// <summary>
        /// Get Entity By ProcInstID
        /// </summary> 
        public static async Task<T> GetByProcInstIdAsync<T>(string procInstId) where T : class, new()
        {
            try
            {
                string tbname = typeof(T).Name;
                string sql = string.Format("SELECT * FROM {0} WHERE ProcInstID='{1}'", tbname, procInstId);
               // using (var conn = new SqlConnection(connectionString))
                {
                    return await Conn.QueryFirstOrDefaultAsync<T>(sql);
                }
            }
            catch (Exception ex)
            {
               // SystemLog.WriteError(ex);
                return null;
            }
        }
        #endregion
    }
}
